<template>
  <div>
    <div class="search-content">
      <i class="el-icon-search" @click="showBox"></i>
      <transition name="el-fade-in-linear">
        <el-autocomplete
          v-if="isShow"
          class="input"
          v-model="input"
          autofocus
          @blur="onBlur"
          :fetch-suggestions="querySearch"
          :trigger-on-focus="false"
          placeholder="站内搜索"
          @select="handleSelect"
        ></el-autocomplete>
      </transition>
    </div>
  </div>
</template>

<script>
import { options } from 'runjs'
export default {
  name: 'SiteSearch',

  data() {
    return {
      restaurants: [],
      input: '',
      isShow: false
    }
  },

  methods: {
    showBox() {
      this.isShow = true
    },
    onBlur() {
      if (this.input === '') {
        this.isShow = false
      }
    },
    querySearch(queryString, cb) {
      // console.log(this.restaurants)
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
      }
    },
    handleSelect(item) {
      this.$router.push(item.path)
    },
    loadAll() {
      const options = []
      this.routes.forEach(item=> {
        // debugger
        const opt = {"value":'', "path": ''}
        if(!item.hidden) {
          if (!item.meta){
            opt.value = this.$t(item.children[0].meta.title)
            opt.path = item.redirect || item.path + '/' + item.children[0].path
            options.push(opt)
          }else {
            const opt = {"value":'', "path": ''}

            opt.value = this.$t(item.meta.title)
            opt.path = item.redirect
            options.push(opt)

            item.children.forEach(child => {
              const opt = {"value":'', "path": ''}

              opt.value = this.$t(child.meta.title)
              opt.path = item.path + '/' + child.path
              return options.push(opt)
            })
          }
        }else {
          return
        }
        // this.restaurants = options
      })
      return options
    }
  },
  mounted() {
    this.restaurants = this.loadAll()
  },
  computed: {
    routes() {
      return this.$router.options.routes
    }
  }
}
</script>

<style lang="scss" scoped>
.search-content{
  display: flex;
  margin-right: 10px;
  .el-icon-search{
    margin-right: 5px;
    color: #fff;
    font-size: 20px;
    vertical-align: -5px;
    line-height: 50px;
  }
  ::v-deep .el-input__inner{
    height: 30px!important;
  }
}
</style>
